using Microsoft.UI.Dispatching;

namespace MultiAgentsClient.Manager;

public partial class NavigationManager : ManagerBase
{
    private readonly Frame? frame;

    private static Type? currentPageType;
    public record NavigationCommand(Type PageType);
    public static Type? CurrentPage
    {
        get => currentPageType;

        set
        {
            currentPageType = value;
        }
    }

    private readonly SemaphoreSlim Semaphore = new(1);

    public NavigationManager(Frame frame)
    {
        this.frame = frame;

        eventBus.Subscribe<NavigationCommand>(cmd => { Task.Run(() => NavigationTo(cmd)); });
    }

    private void NavigationTo(NavigationCommand cmd)
    {
        Semaphore.Wait();
        try
        {
            DispatcherQueue.TryEnqueue(() =>
            {
                frame?.Navigate(cmd.PageType, "");
                currentPageType = cmd.PageType;
            });
        }
        finally
        {
            Semaphore.Release();
        }
    }

    public static Task IsCurrentPage(Type targetPageType)
    {
        while (currentPageType != targetPageType)
        {
            Task.Delay(100);
        }
        return Task.CompletedTask;
    }
}
